package com.ajieee.merge.exception;

import com.ajieee.merge.entity.common.result.ApiResult;
import com.ajieee.merge.enums.common.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.stream.Collectors;

/**
 * @author ajieee
 * @date 2025-10-25
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

	@ExceptionHandler(AuthException.class)
	public ApiResult<Void> handleAuthException(AuthException e) {
		log.warn("{} 登录失败, 原因: {}", e.getUsername(), e.getDetailMessage());
		return ApiResult.error(e.getCode(), e.getMessage());
	}

	@ExceptionHandler(BizWarnException.class)
	public ApiResult<Void> handleBizWarnException(BizWarnException e) {
		log.warn("业务异常: {}", e.getMessage());
		return ApiResult.error(e.getCode(), e.getMessage());
	}

	@ExceptionHandler(MethodArgumentNotValidException.class)
	public ApiResult<Void> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
		String message = e.getBindingResult().getAllErrors().stream()
				.map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining(";"));
		log.warn("参数异常: {}", message);
		return ApiResult.error(ResultCode.PARAM_ERROR.getCode(), message);
	}

}
